package com.cn.ByteStream;

import org.junit.Test;

import java.io.*;

/**
 * 使用 FileInputStream 和 FileOutputStream 读写文件
 */
public class ByteStreamTest1 {

    @Test
    public void test1(){
        String sourcePath = "src/main/resources/test.txt";
        String destPath = "src/main/resources/test1.txt";

        try(FileInputStream fis = new FileInputStream(sourcePath);
            //加true表示追加
            FileOutputStream fos = new FileOutputStream(destPath,true)
        ){
            byte[] buffer = new byte[1024];
            int byteRead;
            while ((byteRead = fis.read(buffer)) != -1){
                fos.write(buffer,0,byteRead);
            }
            System.out.println("文件复制成功");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 使用 BufferedInputStream 和 BufferedOutputStream 优化性能**
     */
    @Test
    public void test2(){
        String sourcePath = "src/main/resources/test.txt";
        String destPath = "src/main/resources/test2.txt";

        try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourcePath));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destPath,true))){
            byte[] buffer = new byte[1024];
            int byteRead;
            while((byteRead = bis.read(buffer)) != -1){
                bos.write(buffer, 0, byteRead);
            }
            //确保缓冲区数据写入
            bos.flush();
            System.out.println("文件复制成功");
        }catch (IOException e){
            e.printStackTrace();
        }

    }


}
